import React, {
  Component
} from 'react';
import {
  NativeModules,
  StyleSheet,
  Text,
  View,
  Image,
  TouchableOpacity,
  Platform,
  NativeEventEmitter
} from 'react-native';
import api from '@/api';
import { uploadImage } from '@/config';
import { cache, msg, Button, AsyncStorage } from '@/common';
import { isAndroid, px2dp, mainBgColorWhite } from '@/styles';

const { Submit } = Button;
let CookieManager = NativeModules.RNCookieManagerIOS;
/**
 * @author shuchang kanglang
 * @description 身份认证
 * @createDate 2020/6/24
 *
 */
const FaceCheckHelper = Platform.select({
  android: () => NativeModules.PushFaceViewControllerModule,
  ios: () => NativeModules.RNIOSExportJsToReact
})();
const NativeModule = new NativeEventEmitter(FaceCheckHelper);

// 人脸识别节流
let isFacing = false;
export default class IdCard extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isOk1: false,
      isOk2: false,
      idcard1: require('../../../images/wl/idcard1.png'),
      idcard2: require('../../../images/wl/idcard2.png'),
      visible: false,
      idcardIos1: '../../../images/wl/idcard1.png',
      idcardIos2: '../../../images/wl/idcard2.png',
      routerFrom: '' // 用于完善资料判断
    };
  }

  componentDidMount() {
    const { navigation } = this.props;
    const state = navigation.state || {};
    const params = state.params || {};
    // NativeModule.addListener('FaceCheckHelper', (data) => this.faceCheckCallback(data));
    if (Platform.OS === 'android') {
      NativeModule.addListener('FaceCheckHelper', (data) => this.faceCheckCallback(data.images.bestImage));
    } else {
      this.addListenerIOS();
    }
  }

  // ios人脸检测回调
  addListenerIOS = () => {
    const { GJCommonEmitter } = NativeModules;
    const commonManagerEmitter = new NativeEventEmitter(GJCommonEmitter);
    this.listener = commonManagerEmitter.addListener(
      'FaceCheckHelper',
      (dataJsonStr) => {
        const { originalImageEncryptStr } = JSON.parse(dataJsonStr);
        // originalImageEncryptStr base64 图片
        this.faceCheckCallback(originalImageEncryptStr);
      },
    );
  };

  render() {
    const { idcard1, idcard2, isOk1, isOk2, visible, } = this.state;
    return (
      <View style={styles.container}>
        <TouchableOpacity
          activeOpacity={1}
          onPress={() => this._selectImg1(0)}
        >
          <Image
            style={styles.idCardBgImg}
            source={idcard1}
            resizeMode='stretch'
          />
          <View style={styles.textWrap}>
            <Text
              style={styles.tips}
            >
              {' '}
              点击拍摄或上传人像面
            </Text>
            {
              isOk1 ?
                <Image
                  style={{ width: px2dp(14), height: px2dp(14), marginLeft: 4 }}
                  source={require('../../../images/icons/icon_success_green.png')}
                  resizeMode='stretch'
                /> : null
            }

          </View>
        </TouchableOpacity>

        <TouchableOpacity
          activeOpacity={1}
          onPress={
            () => this._selectImg1(1)
          }
        >
          <Image
            style={styles.idCardBgImg}
            source={idcard2}
            resizeMode='stretch'
          />
          <View style={styles.textWrap}>
            <Text style={styles.tips}>点击拍摄或上传国徽面</Text>
            {
              isOk2 ?
                <Image
                  style={{ width: px2dp(14), height: px2dp(14), marginLeft: 4, }}
                  source={require('../../../images/icons/icon_success_green.png')}
                  resizeMode='stretch'
                />
                : null
            }
          </View>
        </TouchableOpacity>

        <Submit
          text='提交'
          disabled={!isOk1 || !isOk2}
          boxStyle={{
            width: px2dp(640),
            height: px2dp(96),
            borderRadius: px2dp(48),
            position: 'absolute',
            bottom: px2dp(40)
          }}
          btnStyle={{}}
          btnTextStyle={{
            fontSize: px2dp(36),
          }}
          onClick={() => { this._toLive(); }}
        />
      </View>
    );
  }

  _handleBack() {
    const { navigator } = this.props;
    if (navigator && navigator.getCurrentRoutes().length > 1) {
      navigator.pop();
      return true;
    }
    return false;
  }

  // onLayout = (event) => {
  //   topHeight = event.nativeEvent.layout.height;
  //   console.log(height, topHeight);
  // }

  _selectImg1(data, i) {
    console.log('🚀🚀🚀wimi======>>>1111',);
    NativeModules.DataModule.chooseImage((path, imageBase64) => {
      this.IdCardUpload(data, path);
    });
  }

  IdCardUpload(type, path) {
    NativeModules.WindowModule.showLoading();
    uploadImage('upload?dirName=idCard', path).then(res => {
      // 请求成功
      if (res.success) {
        // 获取图片地址
        api.file.getFile({ fileId: res.data.localId }).then(imgData => {
          if (type === 0) {
            this.setState({
              idCardFrontUrl: res.data.localId,
              idcard1: { uri: imgData.data },
              isOk1: true
            });
          } else {
            this.setState({
              idCardBackUrl: res.data.localId,
              idcard2: { uri: imgData.data },
              isOk2: true
            });
          }
        });
      } else {
        NativeModules.WindowModule.showWindow({ content: '上传失败，请重试', onlyRightBtn: '1' }, (e) => { });
        // 服务器返回异常，设定服务器返回的异常信息保存在 header.msgArray[0].desc
        console.log('--->', res.header.msgArray[0].desc);
      }
      NativeModules.WindowModule.dismissLoading();
    }).catch(err => {
      console.log(err);
      NativeModules.WindowModule.dismissLoading();
      // 请求失败
      NativeModules.WindowModule.showWindow({ content: '上传出错，请重试', onlyRightBtn: '1' }, (e) => { });
    });
  }

  _toLive = () => {
    const { isOk1, isOk2, idCardFrontUrl, idCardBackUrl } = this.state;
    console.log('idCardFront', idCardFrontUrl);
    console.log('idCardBack', idCardBackUrl);
    if (!idCardFrontUrl || !idCardBackUrl) {
      NativeModules.WindowModule.showWindow({ content: '请先上传证件', onlyRightBtn: '1' }, (e) => { });
      return;
    }
    if (isOk1 && isOk2) {
      this.setState({ visible: true });

      api.user.getUserInfo().then(res => {
        if (res.success) {
          const { navigation } = this.props;
          const state = navigation.state || {};
          const params = state.params || {};
          const { code } = params;
          const { userId } = res.data;
          const certiParams = {
            idCardFrontUrl,
            idCardBackUrl,
            userId
          };
          api.user.certificatUser(certiParams).then(res => {
            this.setState({ visible: false });
            if (res.success) {
              // 0 可以直接认证，无须合并账户  1 有重复账户，需合并账户
              if (!res.data.state) {
                api.user.getUserInfo().then(res => {
                  if (res.success) {
                    AsyncStorage.setItem(cache.USER_INFO, res.data);
                    msg.emit('router: goToNext', {
                      routeName: 'FeedBackDriverCer',
                      title: '认证成功',
                      status: 1,
                      routerFrom: 'RoleSwitch',
                    });
                  }
                });
              }
              if (res.data.state === 1) {
                // msg.emit('app:tip', { text: '身份信息已存在' });
                msg.emit('app:messageBox', {
                  isVisible: true,
                  text: res.data.remark,
                  okText: '我要换绑',
                  cancelText: '取消',
                  okFn: () => {
                    this.toFace();
                  },
                });
              }
            } else {
              msg.emit('app:messageBox', {
                isVisible: true,
                text: res.msg,
                okText: '确定',
                okFn: () => {},
              });
            }
          });
        } else {
          this.setState({ visible: false });
        }
      });
    }
  }

  toFace = () => {
    let obj = {
      // 质量校验设置
      quality: {
        minFaceSize: 200, // 设置最小检测人脸阈值 默认是200
        cropFaceSizeWidth: 400, // 设置截取人脸图片大小 默认是 400
        occluThreshold: 0.5, // 设置人脸遮挡阀值 默认是 0.5
        illumThreshold: 40, // 设置亮度阀值 默认是 40
        blurThreshold: 0.7, // 设置图像模糊阀值 默认是 0.7
        EulurAngleThrPitch: 10, // 设置头部姿态角度 默认是 10
        EulurAngleThrYaw: 10, // 设置头部姿态角度 默认是 10
        EulurAngleThrRoll: 10, // 设置头部姿态角度 默认是 10
        isCheckQuality: true, // 设置是否进行人脸图片质量检测 默认是 true
        conditionTimeout: 10, // 设置超时时间 默认是 10
        notFaceThreshold: 0.6, // 设置人脸检测精度阀值 默认是0.6
        maxCropImageNum: 1, // 设置照片采集张数 默认是 1
      },
      liveActionArray: [
        // 0, //眨眨眼
        1, // 张张嘴
        // 2, //向右摇头
        // 3, //向左摇头
        // 4, //抬头
        // 5, //低头
        // 6, //摇头
      ], // 活体动作列表
      order: false, // 是否按顺序进行活体动作
      sound: true, // 提示音，默认不开启
    };
    FaceCheckHelper.openPushFaceViewController(obj);
  }

  faceCheckCallback(data) {
    this.setState({ visible: true });
    console.log('--识别到的内容--', data);
    if (isFacing) {
      return;
    }
    isFacing = true;
    api.user.ocrFace({ image: data }).then(res => {
      isFacing = false;
      this.setState({ visible: false });
      if (res.success) {
        msg.emit('app:messageBox', {
          isVisible: true,
          text: '合并成功！请重新登录',
          okText: '确定',
          isClickBg: false,
          okFn: () => {
            this._loginout();
          },
        });
      } else {
        msg.emit('app:messageBox', {
          isVisible: true,
          text: res.msg,
          okText: '确定',
        });
      }
    }).catch(() => {
      isFacing = false;
    });
  }

  _loginout = () => {
    api.user.logout().then(resOut => {
      if (resOut.success) {
        if (!isAndroid) {
          CookieManager.clearAll().then((res) => {
            console.log('CookieManager.clearAll =>', res);
          });
        }
        msg.emit('router: goToNext', {
          routeName: 'LoginView',
          routerFrom: 'IdCard'
        });
      } else {
        NativeModules.WindowModule.showWindow(
          { content: res.msg, onlyRightBtn: '1' },
          (e) => { },
        );
      }
    });
  };
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: mainBgColorWhite,
    alignItems: 'center'
  },
  idCardBgImg: {
    width: px2dp(520),
    height: px2dp(312),
    marginTop: px2dp(80)
  },
  textWrap: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center'
  },
  tips: {
    color: '#999796'
  },

});
